# -*- coding: utf-8 -*-

from flask import Flask, current_app
from logging.config import dictConfig
from flask_cors import CORS
from traceback import format_exc
from celery import Celery
from config import CELERY_CONFIG
from app.utils.redis_pool import RedisPool
from app.utils.response_format import RET, error_map, resp_json

# celery对象
celery_app = Celery(__name__, **CELERY_CONFIG)
redis_pool = RedisPool()


def create_app():
    # 创建Flask实例应用程序
    app = Flask(__name__, static_folder='../static')

    # 集成配置文件
    app.config.from_pyfile('../config.py')

    # 跨域设置
    CORS(app, supports_credentials=True)

    # 项目日志配置
    dictConfig(app.config.get('LOGGING'))

    # 配置蓝图
    from app.views import config_blueprint
    config_blueprint(app)

    # 全局捕获异常
    @app.errorhandler(Exception)
    def err_handler_validate(e):
        current_app.logger.error(format_exc())
        return resp_json(None, status=RET.UNKOWNERR, message=error_map[RET.UNKOWNERR])

    return app
